package org.springframework.samples.countries.web.translate;

import java.io.InputStream;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Type;
import org.springframework.samples.countries.web.bom.History;
import org.springframework.web.servlet.support.RequestContext;

import pikes.ecma.SourceElement;
import pikes.ecma.SourceElements;
import pikes.peak.RequestProperty;

public abstract class EventHandler implements RequestProperty<SourceElement> {

	protected static final Log translatorLogger = LogFactory.getLog("Translator");

	private SourceElements code = new SourceElements();

	protected History history = new History();

	protected EventHandler() {
		try {
			String newName = Type.getInternalName(this.getClass()) + ".class";
			translatorLogger.info(newName);
			InputStream is = this.getClass().getClassLoader().getResourceAsStream(newName);
			if (is == null) {
				throw new NullPointerException();
			}
			ClassReader cr = new ClassReader(is);
			cr.accept(new EventHandlerTranslator("onEvent", code), true);
			translatorLogger.info("Result: " + code);
		}
		catch (Exception e) {
			translatorLogger.warn("Can't translate class", e);
		}
	}

	public SourceElement getValue(Map model, RequestContext requestContext) throws Exception {
		return code;
	}

	@ClientSide
	abstract protected void onEvent();
}
